<template>
  <div class="goods-image">
    <div
      v-if="!isOutside"
      class="large"
      :style="{ backgroundImage: `url(${goodsList[curIndex]})`,backgroundPositionX:positionX+'px',backgroundPositionY:positionY+'px' }"
    ></div>
    <div class="middle" ref="target">
      <img :src="goodsList[curIndex]" alt="" />
      <!-- 蒙层容器 -->
      <div v-if="!isOutside" class="layer" :style="{left:left+'px',top:top+'px'}"></div>
    </div>
    <ul class="small">
      <li
        :class="{ active: curIndex === i }"
        @mouseenter="curIndex=i"
        v-for="(img, i) in goodsList"
        :key="i"
      >
        <img :src="img" alt="" />
      </li>
    </ul>
  </div>
</template>
<script>
import { ref, watch } from 'vue'
import { useMouseInElement } from '@vueuse/core'
export default {
  name: 'GoodsImage',
  props: {
    goodsList: {
      type: Array,
      defalut: () => {
        return []
      }
    }
  },
  setup () {
    const curIndex = ref(0)
    const target = ref(null)
    const { elementX, elementY, isOutside } = useMouseInElement(target)
    const left = ref(0)
    const top = ref(0)
    const positionX = ref(0)
    const positionY = ref(0)
    watch([elementX, elementY], () => {
      // 横向控制
      if (elementX.value < 100) {
        // left = 0
        left.value = 0
      }
      if (elementX.value > 300) {
        // left = 200
        left.value = 200
      }
      if (elementX.value < 300 && elementX.value > 100) {
        left.value = elementX.value - 100
      }
      // 纵向控制
      if (elementY.value < 100) {
        top.value = 0
      }
      if (elementY.value > 300) {
        top.value = 200
      }
      if (elementY.value < 300 && elementY.value > 100) {
        top.value = elementY.value - 100
      }
      positionX.value = -left.value * 2
      positionY.value = -top.value * 2
    })
    return {
      curIndex,
      target,
      isOutside,
      left,
      top,
      positionX,
      positionY
    }
  }
}
</script>
<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  .layer {
    width: 200px;
    height: 200px;
    background: rgba(0, 0, 0, 0.2);
    left: 0;
    top: 0;
    position: absolute;
  }
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    z-index: 500;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }
  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,
      &.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>
